<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/myblogs/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/myblogs/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/myblogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/myblogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/myblogs/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/myblogs/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/myblogs/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/myblogs/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/myblogs/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />





  <link rel="alternate" href="/myblogs/atom.xml" title="天行健の博客" type="application/atom+xml" />






<meta name="description" content="I do what i do!">
<meta property="og:type" content="website">
<meta property="og:title" content="天行健の博客">
<meta property="og:url" content="https://joy_24.gitee.io/page/2/index.html">
<meta property="og:site_name" content="天行健の博客">
<meta property="og:description" content="I do what i do!">
<meta property="og:locale">
<meta property="article:author" content="Joy Wang">
<meta property="article:tag" content="Java, Spring, Mybatis, SpringMvc, redis">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://joy_24.gitee.io/page/2/"/>





  <title>天行健の博客</title>
  








<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left 
  page-home">
    <div class="headband"></div>
    <a target="_blank" rel="noopener" href="https://github.com/JoyWJ" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>


    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/myblogs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">天行健の博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个开发博客的初学者。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/myblogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/myblogs/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/myblogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/myblogs/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/myblogs/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/myblogs/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
  <section id="posts" class="posts-expand">
    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joy_24.gitee.io/myblogs/2020/12/30/fx-ui-CheckBox/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblogs/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="天行健の博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/myblogs/2020/12/30/fx-ui-CheckBox/" itemprop="url">JavaFX UI之复选框（CheckBox）组件</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-30T16:08:14+08:00">
                2020-12-30
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/JavaFx/" itemprop="url" rel="index">
                    <span itemprop="name">JavaFx</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  946
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  4
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <a id="more"></a>

<p>尽管Checkbox和Radio Button看起来相似，但是它不能组合到Toggle Group来使得同时选中多项。</p>
<p>图6-1显示一个应用程序的截图，其中包含三个checkbox可以控制应用程序工具栏图标的显示与否。</p>
<p><img src="/myblogs/2020/12/30/fx-ui-CheckBox/3-6-1-checkboxes.png"></p>
<h4 id="创建一个Checkbox"><a href="#创建一个Checkbox" class="headerlink" title="创建一个Checkbox"></a>创建一个Checkbox</h4><p>例6-1 创建CheckBox</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//一个不带文字标题的checkbox</span></span><br><span class="line">CheckBox cb1 = <span class="keyword">new</span> CheckBox();</span><br><span class="line"><span class="comment">//一个带有文字标题的checkbox</span></span><br><span class="line">CheckBox cb2 = <span class="keyword">new</span> CheckBox(<span class="string">&quot;Second&quot;</span>);</span><br><span class="line"> </span><br><span class="line">cb1.setText(<span class="string">&quot;First&quot;</span>);</span><br><span class="line">cb1.setSelected(<span class="keyword">true</span>);</span><br></pre></td></tr></table></figure>

<p>一旦你已经创建了一个Checkbox，你可以通过JavaFX API中的方法来修改它。例6-1中，通过setText 方法为cb1设置了文本标题，调用setSelected方法并传入true，使得cb1在应用程序启动时是选中状态。</p>
<h4 id="定义状态"><a href="#定义状态" class="headerlink" title="定义状态"></a>定义状态</h4><p>Checkbox的状态可以是定义的或者未定义的。当它被定义后，你可以选中或者取消选中它。但是当它未被定义时，它不能被选中或者取消选中。组合使用CheckBox 类的setSelected 和setIndeterminate 方法来为CheckBox指定状态。表格6-1展示了Checkbox基于INDETERMINATE和SELECTED 属性的三种状态。</p>
<p>表格6-1 CheckBox 的状态</p>
<p><img src="/myblogs/2020/12/30/fx-ui-CheckBox/status.png"></p>
<p>在你的应用程序中，当需要用Checkbox展示多种混合状态的界面元素时，你可能需要启动Checkbox的三种状态。比如：是，否，不适用。CheckBox对象的allowIndeterminate属性决定了Checkbox是否在所有的三个状态之间循环变换：选中的，非选中的，未定义的。如果属性值是true，Checkbox将在这三个状态之间循环。如果属性值是false，Checkbox将在选中和非选中状态之间循环。下一节介绍的应用程序构造了三个Checkbox，且只启用了两个状态。</p>
<h4 id="设置行为"><a href="#设置行为" class="headerlink" title="设置行为"></a>设置行为</h4><p>代码片段例6-2创建了三个Checkbox，如果某个Checkbox被选中，其对应的图标将会显示在工具栏中。</p>
<p>例6-2 为CheckBox设置行为</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> javafx.application.Application;</span><br><span class="line"><span class="keyword">import</span> javafx.scene.layout.StackPane;</span><br><span class="line"><span class="keyword">import</span> javafx.beans.value.ObservableValue;</span><br><span class="line"><span class="keyword">import</span> javafx.geometry.Insets;</span><br><span class="line"><span class="keyword">import</span> javafx.geometry.Pos;</span><br><span class="line"><span class="keyword">import</span> javafx.scene.Group;</span><br><span class="line"><span class="keyword">import</span> javafx.scene.Scene;</span><br><span class="line"><span class="keyword">import</span> javafx.scene.control.*;</span><br><span class="line"><span class="keyword">import</span> javafx.scene.image.Image;</span><br><span class="line"><span class="keyword">import</span> javafx.scene.image.ImageView;</span><br><span class="line"><span class="keyword">import</span> javafx.scene.layout.HBox;</span><br><span class="line"><span class="keyword">import</span> javafx.scene.layout.VBox;</span><br><span class="line"><span class="keyword">import</span> javafx.scene.paint.Color;</span><br><span class="line"><span class="keyword">import</span> javafx.scene.shape.Rectangle;</span><br><span class="line"><span class="keyword">import</span> javafx.stage.Stage;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CheckboxSample</span> <span class="keyword">extends</span> <span class="title">Application</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line">    Rectangle rect = <span class="keyword">new</span> Rectangle(<span class="number">90</span>, <span class="number">30</span>);</span><br><span class="line">    <span class="keyword">final</span> String[] names = <span class="keyword">new</span> String[]&#123;<span class="string">&quot;Security&quot;</span>, <span class="string">&quot;Project&quot;</span>, <span class="string">&quot;Chart&quot;</span>&#125;;</span><br><span class="line">    <span class="keyword">final</span> Image[] images = <span class="keyword">new</span> Image[names.length];</span><br><span class="line">    <span class="keyword">final</span> ImageView[] icons = <span class="keyword">new</span> ImageView[names.length];</span><br><span class="line">    <span class="keyword">final</span> CheckBox[] cbs = <span class="keyword">new</span> CheckBox[names.length];</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        launch(args);</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">(Stage stage)</span> </span>&#123;</span><br><span class="line">        Scene scene = <span class="keyword">new</span> Scene(<span class="keyword">new</span> Group());</span><br><span class="line">        stage.setTitle(<span class="string">&quot;Checkbox Sample&quot;</span>);</span><br><span class="line">        stage.setWidth(<span class="number">250</span>);</span><br><span class="line">        stage.setHeight(<span class="number">150</span>);</span><br><span class="line"> </span><br><span class="line">        rect.setArcHeight(<span class="number">10</span>);</span><br><span class="line">        rect.setArcWidth(<span class="number">10</span>);</span><br><span class="line">        rect.setFill(Color.rgb(<span class="number">41</span>, <span class="number">41</span>, <span class="number">41</span>));</span><br><span class="line"> </span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; names.length; i++) &#123;</span><br><span class="line">            <span class="keyword">final</span> Image image = images[i] =</span><br><span class="line">                <span class="keyword">new</span> Image(getClass().getResourceAsStream(names[i] + <span class="string">&quot;.png&quot;</span>));</span><br><span class="line">            <span class="keyword">final</span> ImageView icon = icons[i] = <span class="keyword">new</span> ImageView();</span><br><span class="line">            <span class="keyword">final</span> CheckBox cb = cbs[i] = <span class="keyword">new</span> CheckBox(names[i]);</span><br><span class="line">            cb.selectedProperty().addListener(</span><br><span class="line">                    (ObservableValue&lt;? extends Boolean&gt; ov,</span><br><span class="line">                    Boolean old_val, Boolean new_val) -&gt; &#123;</span><br><span class="line">                        icon.setImage(new_val ? image : <span class="keyword">null</span>);                </span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        VBox vbox = <span class="keyword">new</span> VBox();</span><br><span class="line">        vbox.getChildren().addAll(cbs);</span><br><span class="line">        vbox.setSpacing(<span class="number">5</span>);</span><br><span class="line"> </span><br><span class="line">        HBox hbox = <span class="keyword">new</span> HBox();</span><br><span class="line">        hbox.getChildren().addAll(icons);</span><br><span class="line">        hbox.setPadding(<span class="keyword">new</span> Insets(<span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">5</span>));</span><br><span class="line"> </span><br><span class="line">        StackPane stack = <span class="keyword">new</span> StackPane();</span><br><span class="line"> </span><br><span class="line">        stack.getChildren().add(rect);</span><br><span class="line">        stack.getChildren().add(hbox);</span><br><span class="line">        StackPane.setAlignment(rect, Pos.TOP_CENTER);                </span><br><span class="line"> </span><br><span class="line">        HBox root = <span class="keyword">new</span> HBox();</span><br><span class="line">        root.getChildren().add(vbox);</span><br><span class="line">        root.getChildren().add(stack);</span><br><span class="line">        root.setSpacing(<span class="number">40</span>);</span><br><span class="line">        root.setPadding(<span class="keyword">new</span> Insets(<span class="number">20</span>, <span class="number">10</span>, <span class="number">10</span>, <span class="number">20</span>));</span><br><span class="line"> </span><br><span class="line">        ((Group) scene.getRoot()).getChildren().add(root);</span><br><span class="line"> </span><br><span class="line">        stage.setScene(scene);</span><br><span class="line">        stage.show();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>循环遍历数组names来创建一组Checkbox和一组与之对应的Icon。比如，第一个Checkbox cbs[0]被指定了文字标题“Security“。同时，第一个Icon的image对象被创建时，image[0] 接受“Security.png”作为getResourceStream 方法的文件名。如果一个指定的checkbox被选中，其对应的image对象会被指定给icon。而如果一个Checkbox被取消选中，icon对象会接收一个空image对象，icon就不会被渲染出来。</p>
<p>图6-2显示了Security和Chart选中，而Project未选中时的应用程序运行结果。</p>
<p>图6-2</p>
<p><img src="/myblogs/2020/12/30/fx-ui-CheckBox/3-6-2-checkboxes-two.png"></p>
<p>相关API文档</p>
<ul>
<li><p>CheckBox</p>
</li>
<li><p>JavaFX CSS Specification</p>
</li>
</ul>

          
        
      
    </div>
    
    
    
    
    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joy_24.gitee.io/myblogs/2020/12/30/fx-ui-ToggleButton/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblogs/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="天行健の博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/myblogs/2020/12/30/fx-ui-ToggleButton/" itemprop="url">JavaFX UI之开关按钮（Toggle Button）组件</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-30T09:04:21+08:00">
                2020-12-30
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/JavaFx/" itemprop="url" rel="index">
                    <span itemprop="name">JavaFx</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.1k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  4
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>ToggleButton类，它是JavaFX API中另一种可用的按钮。</p>
<p>两个或以上的Toggle Button可以组合在一个Group中，同时只有一个Toggle Button可以被选中，或者都无需选中。图5-1是在一个Group中组合了三个Toggle Button的应用程序屏幕截图。应用程序会根据选中的Toggle<br>Button绘制一个特定颜色的矩形。</p>
<p>图5-1 三个Toggle Button</p>
<p><img src="/myblogs/2020/12/30/fx-ui-ToggleButton/3-5-1-toggle-buttons.png"></p>
<h4 id="创建一个Toggle-Button"><a href="#创建一个Toggle-Button" class="headerlink" title="创建一个Toggle Button"></a>创建一个Toggle Button</h4><p>你可以使用ToggleButton 类中三个构造方法的任何一个来为你的应用程序创建一个Toggle Button，如例5-1所示。</p>
<p>例5-1 创建 Toggle Button</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//一个不带任何文本或图标的Toggle Button</span></span><br><span class="line">ToggleButton tb1 = <span class="keyword">new</span> ToggleButton();</span><br><span class="line"><span class="comment">//一个带有文本的Toggle Button </span></span><br><span class="line">ToggleButton tb2 = <span class="keyword">new</span> ToggleButton(<span class="string">&quot;Press me&quot;</span>);</span><br><span class="line"><span class="comment">//一个带有文本和图标的Toggle Button</span></span><br><span class="line">Image image = <span class="keyword">new</span> Image(getClass().getResourceAsStream(<span class="string">&quot;icon.png&quot;</span>));</span><br><span class="line">ToggleButton tb3 = <span class="keyword">new</span> ToggleButton (<span class="string">&quot;Press me&quot;</span>, <span class="keyword">new</span> ImageView(image));</span><br></pre></td></tr></table></figure>

<p>ToggleButton类是Labeled类的扩展，所以你可以为其指定一个文本标题、一个图像，或者同时指定二者。你可以通过Labeled类的setText和setGraphic方法来为ToggleButton指定文本或者图像内容。</p>
<p>一旦你在你的代码中定义了多个Toggle Button，你可以将它们组合到一个Group中，并且设定一个特定的行为。</p>
<h4 id="添加Toggle-Button到Group"><a href="#添加Toggle-Button到Group" class="headerlink" title="添加Toggle Button到Group"></a>添加Toggle Button到Group</h4><p>ToggleButton类的具体实现和RadioButton类非常相似。但是，和Radio Button不同的是，在一个组中并不试图强制选中至少一个Toggle Button。也就是说，点击一个选中状态的Toggle Button就会变为非选中状态，而点击一个组中选中状态的Radio Button则没有响应。</p>
<p>例5-2 组合 Toggle Button 到Group</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> ToggleGroup Group = <span class="keyword">new</span> ToggleGroup();</span><br><span class="line"> </span><br><span class="line">ToggleButton tb1 = <span class="keyword">new</span> ToggleButton(<span class="string">&quot;Minor&quot;</span>);</span><br><span class="line">tb1.setToggleGroup(Group);</span><br><span class="line">tb1.setSelected(<span class="keyword">true</span>);</span><br><span class="line"> </span><br><span class="line">ToggleButton tb2 = <span class="keyword">new</span> ToggleButton(<span class="string">&quot;Major&quot;</span>);</span><br><span class="line">tb2.setToggleGroup(Group);</span><br><span class="line"> </span><br><span class="line">ToggleButton tb3 = <span class="keyword">new</span> ToggleButton(<span class="string">&quot;Critical&quot;</span>);</span><br><span class="line">tb3.setToggleGroup(Group);</span><br></pre></td></tr></table></figure>

<p>例5-2创建了三个Toggle Button，并添加到了一个Toggle Group中。为rb1 Toggle Button调用了setSelected方法，所以在应用程序启动时rb1是选中状态。但是你可以取消选中Minor Toggle</p>
<p>Button，以使应用程序启动时组中没有Toggle Button被选中，如图5-2。</p>
<p>图5-2 三个Toggle Button在一组</p>
<p><img src="/myblogs/2020/12/30/fx-ui-ToggleButton/3-5-2-toggle-buttons-select-300x53.png"></p>
<p>通常，你可以使用一组Toggle Button来为每个Button指定一个特定的行为。下一节会向你说明如何使用三个Toggle Button来改变一个矩形的颜色。</p>
<h4 id="设置行为"><a href="#设置行为" class="headerlink" title="设置行为"></a>设置行为</h4><p>ToggleButton类从Node类继承来的setUserData方法可以帮你为选中项关联一个特别的值。例5-3中，User Data 指示了应该使用哪种颜色来绘制矩形。</p>
<p>例5-3 为Toggle Button 设置 User Data</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">tb1.setUserData(Color.LIGHTGREEN);</span><br><span class="line">tb2.setUserData(Color.LIGHTBLUE);</span><br><span class="line">tb3.setUserData(Color.SALMON);</span><br><span class="line"> </span><br><span class="line">Rectangle rect = <span class="keyword">new</span> Rectangle();</span><br><span class="line">rect.setHeight(<span class="number">50</span>);</span><br><span class="line">rect.setFill(Color.WHITE);</span><br><span class="line">rect.setStroke(Color.DARKGRAY);</span><br><span class="line">rect.setStrokeWidth(<span class="number">2</span>);</span><br><span class="line">rect.setArcHeight(<span class="number">10</span>);</span><br><span class="line">rect.setArcWidth(<span class="number">10</span>);</span><br><span class="line"> </span><br><span class="line"><span class="keyword">final</span> ToggleGroup Group = <span class="keyword">new</span> ToggleGroup();</span><br><span class="line"> </span><br><span class="line">Group.selectedToggleProperty().addListener(            </span><br><span class="line">    (ObservableValue&lt;? extends Toggle&gt; ov, </span><br><span class="line">    Toggle toggle, Toggle new_toggle) -&gt; &#123;</span><br><span class="line">    <span class="keyword">if</span> (new_toggle == <span class="keyword">null</span>)</span><br><span class="line">        rect.setFill(Color.WHITE);</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        rect.setFill((Color) Group.getSelectedToggle().getUserData());</span><br><span class="line">&#125;);</span><br><span class="line"> </span><br><span class="line">rect.setWidth(hbox.getWidth());</span><br></pre></td></tr></table></figure>

<p>ChangeListener<Toggle>对象监听组中的选中项。如果没有Toggle Button被选中，矩形就绘制成白色。如果其中一个Toggle Button被选中，连续调用getSelectedToggle和getUserData方法会返回一个Color来绘制矩形。</Toggle></p>
<p>例如，如果用户选中了tb2 Toggle Button，getSelectedToggle().getUserData()方法将会返回Color.LIGHTBLUE，运行结果如图5-3。</p>
<p>应用程序完整的代码见ToggleButtonSample.java文件。</p>
<h4 id="为Toggle-Button设置样式"><a href="#为Toggle-Button设置样式" class="headerlink" title="为Toggle Button设置样式"></a>为Toggle Button设置样式</h4><p>你可以为Toggle Button添加CSS样式来加强你的应用程序。在JavaFX应用程序中使用CSS和在HTML中使用类似，因为这两者都是基于相同的CSS规范。</p>
<p>首先，你要在ControlStyle.css 文件中为Toggle Button声明样式，如例5-4。</p>
<p>例5-4 为Toggle Button声明不同的颜色</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">.toggle-button1&#123;</span><br><span class="line">    -fx-base: lightgreen;   </span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line">.toggle-button2&#123;</span><br><span class="line">    -fx-base: lightblue;  </span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line">.toggle-button3&#123;</span><br><span class="line">    -fx-base: salmon;   </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其次，在ToggleButtonSample 应用程序中启用这些样式，见例5-5中的实现。</p>
<p>例5-5 为Toggle Button启用CSS样式</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">scene.getStylesheets().add(<span class="string">&quot;togglebuttonsample/ControlStyle.css&quot;</span>);</span><br><span class="line"> </span><br><span class="line">tb1.getStyleClass().add(<span class="string">&quot;toggle-button1&quot;</span>);</span><br><span class="line">tb2.getStyleClass().add(<span class="string">&quot;toggle-button2&quot;</span>);</span><br><span class="line">tb3.getStyleClass().add(<span class="string">&quot;toggle-button3&quot;</span>);</span><br></pre></td></tr></table></figure>

<p>当把这些代码添加到应用程序后，将会改变Toggle Button的显示效果，如图5-4。</p>
<p><img src="/myblogs/2020/12/30/fx-ui-ToggleButton/3-5-4-toggle-buttons-css-300x199.png"></p>
<p>你可能想尝试一下ToggleButton 类的其他CSS属性，或者应用动画、变换以及其他JavaFX API中的可视化特效。</p>

          
        
      
    </div>
    
    
    
    
    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joy_24.gitee.io/myblogs/2020/12/29/fx-ui-RadioButton/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblogs/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="天行健の博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/myblogs/2020/12/29/fx-ui-RadioButton/" itemprop="url">JavaFX UI之单选按钮（Radio Button）组件</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-29T16:57:08+08:00">
                2020-12-29
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/JavaFx/" itemprop="url" rel="index">
                    <span itemprop="name">JavaFx</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  996
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  4
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <a id="more"></a>

<p>一个Radio Button可以被选中或者取消选中。典型的用法是将多个Radio Button放在一个组中，同一时间内其中只有一个Button可以被选中。这正是Radio Button区别于Toggle Button(开关按钮) 的行为，因为一个组中的所有Toggle Button可以同时全都取消选中</p>
<p>图4-1显示了三个RadioButton样例的截图，其中三个Radio Button被添加到了一个组中。</p>
<p><img src="/myblogs/2020/12/29/fx-ui-RadioButton/3-4-1-radio-buttons.png" alt="图4-1"></p>
<h4 id="创建一个Radio-Button"><a href="#创建一个Radio-Button" class="headerlink" title="创建一个Radio Button"></a>创建一个Radio Button</h4><p>RadioButton类位于JavaFX SDK的 javafx.scene.control 包中，它提供了两个构造方法来创建其实例。例4-1展示了两个RadioButton。rb1是由无参构造方法创建。这个Radio Button 的文字说明(text caption)是通过setText方法设置的。rb2的文字说明则是通过对应的构造方法定义的。</p>
<p>例4-1</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//标签为空的Radio Button</span></span><br><span class="line">RadioButton rb1 = <span class="keyword">new</span> RadioButton();</span><br><span class="line"> </span><br><span class="line"><span class="comment">//设置标签文字</span></span><br><span class="line">rb1.setText(<span class="string">&quot;Home&quot;</span>);</span><br><span class="line"> </span><br><span class="line"><span class="comment">//指定标签文字的Radio Button</span></span><br><span class="line">RadioButton rb2 = <span class="keyword">new</span> RadioButton(<span class="string">&quot;Calendar&quot;</span>);</span><br></pre></td></tr></table></figure>

<p>你可以通过调用setSelected方法并指定参数值为true来明确选中一个Radio Button。如果你需要检查某个Radio Button是否被用户选中，可以使用isSelected方法。</p>
<p>因为RadioButton类是Labeled类的一个扩展，所以你不仅可以指定文字描述，还可以指定一个图像。你可以使用setGraphic方法来指定一个图像。例4-2展示了如何在你的应用程序中实现一个带图像的Radio Button。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Image image = <span class="keyword">new</span> Image(getClass().getResourceAsStream(<span class="string">&quot;ok.jpg&quot;</span>));</span><br><span class="line">RadioButton rb = <span class="keyword">new</span> RadioButton(<span class="string">&quot;Agree&quot;</span>);</span><br><span class="line">rb.setGraphic(<span class="keyword">new</span> ImageView(image));</span><br></pre></td></tr></table></figure>

<h4 id="添加Radio-Button到Group"><a href="#添加Radio-Button到Group" class="headerlink" title="添加Radio Button到Group"></a>添加Radio Button到Group</h4><p>Radio Button通常用于呈现一个组中几个相互排斥的选项。ToggleGroup 对象提供与之关联的Radio Button的引用并管理它们，使得同时只有一个Radio Button能被选中。例4-3 创建了一个Toggle Group，和三个Radio Button，将所有Radio Button都添加到了Toggle Group中，并且指定了哪个Radio Button在程序启动时会被选中。</p>
<p>例4-3 创建一组Radio Button</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> ToggleGroup group = <span class="keyword">new</span> ToggleGroup();</span><br><span class="line"> </span><br><span class="line">RadioButton rb1 = <span class="keyword">new</span> RadioButton(<span class="string">&quot;Home&quot;</span>);</span><br><span class="line">rb1.setToggleGroup(group);</span><br><span class="line">rb1.setSelected(<span class="keyword">true</span>);</span><br><span class="line"> </span><br><span class="line">RadioButton rb2 = <span class="keyword">new</span> RadioButton(<span class="string">&quot;Calendar&quot;</span>);</span><br><span class="line">rb2.setToggleGroup(group);</span><br><span class="line"> </span><br><span class="line">RadioButton rb3 = <span class="keyword">new</span> RadioButton(<span class="string">&quot;Contacts&quot;</span>);</span><br><span class="line">rb3.setToggleGroup(group);</span><br></pre></td></tr></table></figure>

<p>当这些Radio Button通过容器布局展现并添加到应用程序中后，运行效果如图4-2所示。</p>
<p><img src="/myblogs/2020/12/29/fx-ui-RadioButton/3-4-2-radio-buttons-group.png"></p>
<h4 id="处理Radio-Button事件"><a href="#处理Radio-Button事件" class="headerlink" title="处理Radio Button事件"></a>处理Radio Button事件</h4><p>通常，在组中的某个Radio Button被选中时，应用程序会执行一个动作。查看例4-4来学习如何根据某个Radio Button的选中来更换图标。</p>
<p>例4-4 处理Radio Button动作</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">ImageView image = <span class="keyword">new</span> ImageView();</span><br><span class="line"> </span><br><span class="line">rb1.setUserData(<span class="string">&quot;Home&quot;</span>)</span><br><span class="line">rb2.setUserData(<span class="string">&quot;Calendar&quot;</span>);</span><br><span class="line">rb3.setUserData(<span class="string">&quot;Contacts&quot;</span>); </span><br><span class="line"> </span><br><span class="line"><span class="keyword">final</span> ToggleGroup group = <span class="keyword">new</span> ToggleGroup();</span><br><span class="line"> </span><br><span class="line">group.selectedToggleProperty().addListener(</span><br><span class="line">    (ObservableValue&lt;? extends Toggle&gt; ov, Toggle old_Toggle,</span><br><span class="line">    Toggle new_Toggle) -&gt; &#123;</span><br><span class="line">        <span class="keyword">if</span> (group.getSelectedToggle() != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">final</span> Image image = <span class="keyword">new</span> Image(</span><br><span class="line">                getClass().getResourceAsStream(</span><br><span class="line">                group.getSelectedToggle().getUserData().toString() +</span><br><span class="line">                <span class="string">&quot;.jpg&quot;</span>));</span><br><span class="line">        icon.setImage(image);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>用户数据(User Data)被指定给了每个Radio Button。ChangeListener<Toggle>对象会检测Group中被选中的开关按钮。然后使用Group的getSelectedToggle方法得到当前选中的Radio Button，并通过调用getUserData方法提取User Data。然后User Data被用来构造成一个图像文件名来加载图像。</Toggle></p>
<p>例如，当rb3被选中时，getSelectedToggle方法会返回rb3的引用，而getUserData方法会返回“Contacts”。因此getResourceAsStream 方法会收到值为“Contacts.jpg” 的字符串作为参数。运行应用程序效果如上图4-1。</p>
<h4 id="为Radio-Button请求焦点"><a href="#为Radio-Button请求焦点" class="headerlink" title="为Radio Button请求焦点"></a>为Radio Button请求焦点</h4><p>在一组Radio Button中，默认情况下第一个Radio Button会最先获得焦点。如果你在第二个Radio Button上调用setSelected方法，其预期结果如图4-3所示。</p>
<p>图4-3 默认焦点设置</p>
<p><img src="/myblogs/2020/12/29/fx-ui-RadioButton/3-4-3-radio-button-focus1.png"></p>
<p>在图中第二个Radio Button被选中了，但第一个Radio Button依然保持着焦点。你可以使用requestFocus方法来更改焦点，见例4-5。</p>
<p>例4-5 为第二个Radio Button请求焦点</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">rb2.setSelected(<span class="keyword">true</span>);</span><br><span class="line">rb2.requestFocus();</span><br></pre></td></tr></table></figure>

<p>代码生效后的运行效果如图4-4。</p>
<p>图4-4 为选中的Radio Button设置焦点</p>
<p><img src="/myblogs/2020/12/29/fx-ui-RadioButton/3-4-4-radio-button-focus2.png"></p>
<p>相关API文档</p>
<ul>
<li>RadioButton</li>
<li>Labeled</li>
<li>ToggleGroup</li>
</ul>

          
        
      
    </div>
    
    
    
    
    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joy_24.gitee.io/myblogs/2020/12/29/fx-ui-Button/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblogs/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="天行健の博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/myblogs/2020/12/29/fx-ui-Button/" itemprop="url">JavaFX UI之按钮（Button）组件</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-29T16:00:17+08:00">
                2020-12-29
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/JavaFx/" itemprop="url" rel="index">
                    <span itemprop="name">JavaFx</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  863
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  3
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <a id="more"></a>

<p>JavaFX API中的Button类用来处理当用户点击一个按钮时执行一个动作(Action)。Button类继承自Labeled类，它可以显示文本，图像，或两者兼而有之。图2-1显示了几个不同效果的按钮，下面就学习如何创建这些类型的按钮。</p>
<p><img src="/myblogs/2020/12/29/fx-ui-Button/3-3-1-button-collections-300x196.png" alt="图3-1"></p>
<h3 id="创建一个按钮"><a href="#创建一个按钮" class="headerlink" title="创建一个按钮"></a>创建一个按钮</h3><p>三种方法创建Button控件</p>
<p>例3-1</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//一个空Button</span></span><br><span class="line">Button button1 = <span class="keyword">new</span> Button();</span><br><span class="line"><span class="comment">//一个指定了文本标题的Button</span></span><br><span class="line">Button button2 = <span class="keyword">new</span> Button(<span class="string">&quot;Accept&quot;</span>);</span><br><span class="line"><span class="comment">//一个指定了文本标题和图标的Button</span></span><br><span class="line">Image imageOk = <span class="keyword">new</span> Image(getClass().getResourceAsStream(<span class="string">&quot;ok.png&quot;</span>));</span><br><span class="line">Button button3 = <span class="keyword">new</span> Button(<span class="string">&quot;Accept&quot;</span>, <span class="keyword">new</span> ImageView(imageOk));</span><br></pre></td></tr></table></figure>

<p>Button类继承自Labeled类，你可以使用以下方法来指定按钮的内容：</p>
<ul>
<li>setText(String text)method——指定文本</li>
<li>setGraphic(Node graphic)method——指定图标</li>
</ul>
<p>例3-2：创建一个只有图标没有文本的按钮</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Image imageDecline = <span class="keyword">new</span> Image(getClass().getResourceAsStream(<span class="string">&quot;not.png&quot;</span>));</span><br><span class="line">Button button5 = <span class="keyword">new</span> Button();</span><br><span class="line">button5.setGraphic(<span class="keyword">new</span> ImageView(imageDecline));</span><br></pre></td></tr></table></figure>

<p>运行结果：</p>
<p><img src="/myblogs/2020/12/29/fx-ui-Button/3-3-2-decline-button.png" alt="图3-2"></p>
<p>上面给按钮设置的图标是一个ImageView对象。然而你也可以使用其他图形对象。例如位于javafx.scene.shape 包中的各种形状。当为按钮同时设置了文本和图形内容时，可以使用setGraphicTextGap方法来设置它们之间的间距。</p>
<p>按钮的默认皮肤区分了以下几种显示状态。图3-3显示了一个带图标按钮的几种默认状态。</p>
<p><img src="/myblogs/2020/12/29/fx-ui-Button/3-3-3-button-states-300x65.png" alt="图3-3"></p>
<h3 id="为Button添加事件（Action）"><a href="#为Button添加事件（Action）" class="headerlink" title="为Button添加事件（Action）"></a>为Button添加事件（Action）</h3><p>当鼠标点击按钮时，首要的功能就是执行一个Action。使用setOnAction的方法来定义当用户点击按钮时将发生什么。例3-3展示了为button2定义一个Action。</p>
<p>例3-3</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">button2.setOnAction((ActionEvent e) -&gt; &#123;</span><br><span class="line">    label.setText(<span class="string">&quot;Accepted&quot;</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>上面代码展示了如何处理一个ActionEvent，这样当用户点击button2时，一个Label的文本被设置为Accepted。</p>
<p>你可以为一个Button设置多个事件处理方法，来执行特定的行为或添加视觉特效。</p>
<h3 id="应用视觉特效"><a href="#应用视觉特效" class="headerlink" title="应用视觉特效"></a>应用视觉特效</h3><p>因为Button类继承自Node类，所以你可以为Button添加javafx.scene.effect包下的任何特效来增强视觉效果。例3-4中, 当onMouseEntered事件被触发时会向button3上添加阴影(DropShadow)特效</p>
<p>例3-4</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">DropShadow shadow = <span class="keyword">new</span> DropShadow();</span><br><span class="line"> </span><br><span class="line"><span class="comment">//当鼠标进入按钮时添加阴影特效</span></span><br><span class="line">button3.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -&gt; &#123;</span><br><span class="line">    button3.setEffect(shadow);</span><br><span class="line">&#125;);</span><br><span class="line"> </span><br><span class="line"><span class="comment">//当鼠标离开按钮时移除阴影效果</span></span><br><span class="line">button3.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -&gt; &#123;</span><br><span class="line">    button3.setEffect(<span class="keyword">null</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>运行这段代码，效果如图3-4所示</p>
<p><img src="/myblogs/2020/12/29/fx-ui-Button/3-3-4-button-with-shadow.png" alt="图3-4"></p>
<h3 id="为Button设置样式"><a href="#为Button设置样式" class="headerlink" title="为Button设置样式"></a>为Button设置样式</h3><p>接下来我们通过使用Skin类中定义的CSS样式来增强按钮的视觉外观。在JavaFX中使用CSS类似于在HTML中使用CSS，因为它们都基于相同的CSS规范。</p>
<p>你可以在一个单独的CSS样式文件中定义样式，然后通过getStyleClass方法在应用程序中使用它。该方法继承自Node类，并且在所有的UI控件中都可用。例3-5和图3-4展示了如何使用CSS及其运行结果。</p>
<p>例3-5</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// CSS文件中的代码</span></span><br><span class="line">.button1&#123;</span><br><span class="line">    -fx-font: <span class="number">22</span> arial;</span><br><span class="line">    -fx-base: #b6e7c9;   </span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">// ButtonSample.java中的代码</span></span><br><span class="line">button1.getStyleClass().add(<span class="string">&quot;button1&quot;</span>);</span><br></pre></td></tr></table></figure>

<p>-fx-font属性设置了button1的字体名称和大小，-fx-base属性重设了按钮的默认颜色。运行这段代码，结果如图3-5所示，button1的背景将变成浅绿色，并且字体会变得比默认字体更大。</p>
<p><img src="/myblogs/2020/12/29/fx-ui-Button/3-3-5-styled-button.png" alt="图3-5"></p>
<p>相关API文档</p>
<ul>
<li>Button</li>
<li>Labeled</li>
</ul>

          
        
      
    </div>
    
    
    
    
    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joy_24.gitee.io/myblogs/2020/12/29/fx-ui-Label/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblogs/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="天行健の博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/myblogs/2020/12/29/fx-ui-Label/" itemprop="url">JavaFX UI之标签（Label）组件</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-29T15:17:11+08:00">
                2020-12-29
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/JavaFx/" itemprop="url" rel="index">
                    <span itemprop="name">JavaFx</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  773
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  3
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <a id="more"></a>

<h3 id="创建Label"><a href="#创建Label" class="headerlink" title="创建Label"></a>创建Label</h3><p>javafx api 为Label提供了三个构建方法，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//一个空Label</span></span><br><span class="line">Label label1 = <span class="keyword">new</span> Label();</span><br><span class="line"><span class="comment">//一个带文本元素的Label</span></span><br><span class="line">Label label2 = <span class="keyword">new</span> Label(<span class="string">&quot;Search&quot;</span>);</span><br><span class="line"><span class="comment">//一个带文本和图标的Label</span></span><br><span class="line">Image image = <span class="keyword">new</span> Image(getClass().getResourceAsStream(<span class="string">&quot;labels.jpg&quot;</span>));</span><br><span class="line">Label label3 = <span class="keyword">new</span> Label(<span class="string">&quot;Search&quot;</span>, <span class="keyword">new</span> ImageView(image));</span><br></pre></td></tr></table></figure>

<p>在创建一个Label之后，可以使用Labeled类的以下方法类设置或者修改文本及图标</p>
<ul>
<li><p>setText(String text)    method —— 指定文本内容</p>
</li>
<li><p>setGraphic(Node graphic)    —— 指定图标</p>
</li>
<li><p>setTextFill()方法可以设定文本的填充颜色，如下图为其添加了一个图标并指定文本的填充颜色：</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Label label1 = <span class="keyword">new</span> Label(<span class="string">&quot;Search&quot;</span>);</span><br><span class="line">Image image = <span class="keyword">new</span> Image(getClass().getResourceAsStream(<span class="string">&quot;labels.jpg&quot;</span>));</span><br><span class="line">label1.setGraphic(<span class="keyword">new</span> ImageView(image));</span><br><span class="line">label1.setTextFill(Color.web(<span class="string">&quot;#0076a3&quot;</span>));</span><br></pre></td></tr></table></figure>

<p>运行结果：</p>
<p><img src="/myblogs/2020/12/29/fx-ui-Label/3-2-2-search-label.png"></p>
<h3 id="设置文本和图标"><a href="#设置文本和图标" class="headerlink" title="设置文本和图标"></a>设置文本和图标</h3><p>如果为标签同时设置文本和图标，可以使用</p>
<ul>
<li><p>setGraphicTextGap()方法来设置它们之间的间距。</p>
</li>
<li><p>setTextAlignment()方法改变其对其方向。</p>
</li>
<li><p>setContentDisplay(ContentDisplay value)方法定义图形与文本的相对位置，ContentDisplay常量的可选值为：居左LEFT，居右:RIGHT，居中CENTER，居上TOP，居下BOTTOM。</p>
</li>
</ul>
<h3 id="设置字体"><a href="#设置字体" class="headerlink" title="设置字体"></a>设置字体</h3><ul>
<li>setFont()方法对Label的默认字体大小进行修改，下面是将label1文本字体大小设置为30 points，并且将字体设置为Arial，label2大小为32 points，字体为Cambria。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用Font类的构造函数来构造Font对象</span></span><br><span class="line">label1.setFont(<span class="keyword">new</span> Font(<span class="string">&quot;Arial&quot;</span>, <span class="number">30</span>));</span><br><span class="line"><span class="comment">//使用Font类的font静态方法</span></span><br><span class="line">label2.setFont(Font.font(<span class="string">&quot;Cambria&quot;</span>, <span class="number">32</span>));</span><br></pre></td></tr></table></figure>

<h3 id="折叠换行文字"><a href="#折叠换行文字" class="headerlink" title="折叠换行文字"></a>折叠换行文字</h3><ul>
<li>setWrapText()    —— 当需要在一个比较小的空间内放置一个Label时，对文本进行折叠换行能够更好的适应布局空间大小。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Label label3 = <span class="keyword">new</span> Label(<span class="string">&quot;A label that needs to be wrapped&quot;</span>);</span><br><span class="line">label3.setWrapText(<span class="keyword">true</span>);</span><br></pre></td></tr></table></figure>

<p>运行结果：</p>
<p><img src="/myblogs/2020/12/29/fx-ui-Label/3-2-3-label-wrap.png"></p>
<p>如果标签的布局区域不仅有宽度限制，还有高度限制，那么可以指定当无法显示所有的文本内容时标签的显示行为。可以使用setTextOverrun(OverrunStyle value)方法来实现，其中OverrunStyle用于指定如何处理不能完成呈现出来的文本。更多内容参考OverrunStyle类型的API文档。</p>
<h3 id="添加视觉特效"><a href="#添加视觉特效" class="headerlink" title="添加视觉特效"></a>添加视觉特效</h3><p>为标签添加视觉特效或者变换效果。下面就是将label2旋转270度，并垂直移动了它的位置。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Label label2 = <span class="keyword">new</span> Label(<span class="string">&quot;Values&quot;</span>);</span><br><span class="line">label2.setFont(<span class="keyword">new</span> Font(<span class="string">&quot;Cambria&quot;</span>, <span class="number">32</span>));</span><br><span class="line">label2.setRotate(<span class="number">270</span>);</span><br><span class="line">label2.setTranslateY(<span class="number">50</span>);</span><br></pre></td></tr></table></figure>

<p>旋转和位移是JavaFX API中典型的变换效果。此外，还可以设置缩放效果，它的作用是当用户将鼠标光标悬停于标签上是将其放大显示。</p>
<p>下面代码设置了缩放效果。当MOUSE_ENTERED事件被触发时，将会通过setScaleX和setScaleY方法设置缩放因子为1.5。当用户将鼠标从标签上移开时会触发MOUSE_EXITED事件，此时缩放比例因子将会还原为1.0，标签将会恢复其原始大小。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">label3.setOnMouseEntered((MouseEvent e) -&gt; &#123;</span><br><span class="line">    label3.setScaleX(<span class="number">1.5</span>);</span><br><span class="line">    label3.setScaleY(<span class="number">1.5</span>);</span><br><span class="line">&#125;);</span><br><span class="line"> </span><br><span class="line">label3.setOnMouseExited((MouseEvent e) -&gt; &#123;</span><br><span class="line">    label3.setScaleX(<span class="number">1</span>);</span><br><span class="line">    label3.setScaleY(<span class="number">1</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>上面代码设置了label3的两种状态，效果如下：</p>
<p><img src="/myblogs/2020/12/29/fx-ui-Label/3-2-4-label-zoom-300x100.png"></p>
<p>相关API文档</p>
<ul>
<li><p>Label</p>
</li>
<li><p>Labeled</p>
</li>
</ul>

          
        
      
    </div>
    
    
    
    
    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joy_24.gitee.io/myblogs/2020/12/09/swing-mouse-event/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblogs/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="天行健の博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/myblogs/2020/12/09/swing-mouse-event/" itemprop="url">Swing开发技巧 —— 鼠标事件</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-09T17:48:56+08:00">
                2020-12-09
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  300
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  1
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="鼠标事件中的接口方法说明"><a href="#鼠标事件中的接口方法说明" class="headerlink" title="鼠标事件中的接口方法说明"></a>鼠标事件中的接口方法说明</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line">.addMouseListener(<span class="keyword">new</span> MouseListener() &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 当用户按下并松开鼠标按钮时发生. 用户在选择或双击图标的时候通常会点击鼠标按钮. </span></span><br><span class="line"><span class="comment">     * 用户如果在松开鼠标之前移动鼠标,点击不会导致鼠标相应事件出现.因为点击鼠标是按下鼠标和松开鼠标的结合, </span></span><br><span class="line"><span class="comment">     * 在事件分配给 mouseClicked() 方法之前, mousePressed() 和 mouseReleased() 方法已同时被调用.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">mouseClicked</span><span class="params">(MouseEvent e)</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 当用户按下鼠标按钮时发生.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">mousePressed</span><span class="params">(MouseEvent e)</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 当用户松开鼠标按钮时发生.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">mouseReleased</span><span class="params">(MouseEvent e)</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 当鼠标离开当前组件并进入你所监听的组件时激活事件.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">mouseEntered</span><span class="params">(MouseEvent e)</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 当鼠标离开你所监听的组件时发生.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">mouseExited</span><span class="params">(MouseEvent e)</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">.addMouseMotionListener(<span class="keyword">new</span> MouseMotionListener() &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 当用户按下鼠标按钮并在松开之前进行移动时发生.在mouseDragged() 后松开鼠标不会导致mouseClicked().</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">mouseDragged</span><span class="params">(MouseEvent e)</span> </span>&#123;                </span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 当鼠标在组件上移动而 不时拖动时发生.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">mouseMoved</span><span class="params">(MouseEvent e)</span> </span>&#123;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>


          
        
      
    </div>
    
    
    
    
    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joy_24.gitee.io/myblogs/2020/12/09/swing-jpanel/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblogs/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="天行健の博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/myblogs/2020/12/09/swing-jpanel/" itemprop="url">Swing开发技巧 —— JPanel篇</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-09T17:39:43+08:00">
                2020-12-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/Swing/" itemprop="url" rel="index">
                    <span itemprop="name">Swing</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  183
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  1
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="设置JPanel边框"><a href="#设置JPanel边框" class="headerlink" title="设置JPanel边框"></a>设置JPanel边框</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">jpanel.setBorder(BorderFactory.createLoweredBevelBorder());</span><br></pre></td></tr></table></figure>

<p>下面是不同类型边框的添加方法</p>
<p>对参数Border对象的定义主要通过BorderFactory进行，这也是本文讨论的重点，根据API的解释：BorderFactory提供标准Border对象的工厂类。在任何可能的地方，此工厂类都将提供对已共享Border实例的引用。下面讨论具体的应用方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">BorderFactory.createLineBorder(Color.red, <span class="number">3</span>)        <span class="comment">//线边框  </span></span><br><span class="line">BorderFactory.createEtchedBorder()                 <span class="comment">//蚀刻边框  </span></span><br><span class="line">BorderFactory.createRaisedBevelBorder()            <span class="comment">//斜面边框(凸)  </span></span><br><span class="line">BorderFactory.createLoweredBevelBorder()           <span class="comment">//斜面边框(凹)  </span></span><br><span class="line">BorderFactory.createTitledBorder(<span class="string">&quot;标题&quot;</span>)          <span class="comment">//标题边框左  </span></span><br><span class="line">BorderFactory.createTitledBorder(<span class="string">&quot;标题&quot;</span>)          <span class="comment">//标题边框右  </span></span><br><span class="line"></span><br><span class="line">setTitleJustification(TitledBorder.RIGHT);  </span><br><span class="line"></span><br><span class="line">BorderFactory.createMatteBorder(<span class="number">1</span>, <span class="number">5</span>, <span class="number">1</span>, <span class="number">1</span>, Color.yellow) <span class="comment">//花色边框  </span></span><br><span class="line">b1 = BorderFactory.createLineBorder(Color.blue, <span class="number">2</span>);  <span class="comment">//组合边框  </span></span><br><span class="line">b2 = BorderFactory.createEtchedBorder();  </span><br><span class="line">BorderFactory.createCompoundBorder(b1, b2)  </span><br></pre></td></tr></table></figure>


          
        
      
    </div>
    
    
    
    
    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joy_24.gitee.io/myblogs/2020/12/09/swing-jfilechooser/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblogs/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="天行健の博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/myblogs/2020/12/09/swing-jfilechooser/" itemprop="url">Swing开发技巧 —— JFileChooser篇</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-09T17:37:03+08:00">
                2020-12-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/Swing/" itemprop="url" rel="index">
                    <span itemprop="name">Swing</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  255
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  1
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="设置JFileChooser-文件选择对话框"><a href="#设置JFileChooser-文件选择对话框" class="headerlink" title="设置JFileChooser-文件选择对话框"></a>设置JFileChooser-文件选择对话框</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">JFileChooser jfc = <span class="keyword">new</span> JFileChooser(); </span><br><span class="line"><span class="comment">//设置默认显示为当前文件夹（.为当前文件夹，也可以配置绝对路径设置） </span></span><br><span class="line">jfc.setCurrentDirectory(<span class="keyword">new</span> File(<span class="string">&quot;.&quot;</span>));</span><br><span class="line"><span class="comment">//设置选择模式（只选文件[ JFileChooser.FILES_ONLY ]、只选文件夹[ JFileChooser.DIRECTORIES_ONLY ]、文件和文件均可选）</span></span><br><span class="line">jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);</span><br><span class="line"><span class="comment">//是否允许多选</span></span><br><span class="line">jfc.setMultiSelectionEnabled(<span class="keyword">true</span>);</span><br><span class="line"><span class="comment">//文件过滤器</span></span><br><span class="line">jfc.addChoosableFileFilter(<span class="keyword">new</span> FileNameExtensionFilter(<span class="string">&quot;zip(*.zip, *.rar)&quot;</span>, <span class="string">&quot;zip&quot;</span>, <span class="string">&quot;rar&quot;</span>));</span><br><span class="line"><span class="comment">//显示文件 打开 对话框（最后调用显示对话框）（弹出一个“打开文件”文件选择器对话框）</span></span><br><span class="line">jfc.showOpenDialog(parent);</span><br><span class="line"><span class="comment">//如果想要改变文件选择对话框 按钮 的名字可以使用如下方式显示对话框（使用自定义批准按钮弹出自定义文件选择器对话框。）</span></span><br><span class="line">jfc.showDialog(<span class="keyword">new</span> JLabel(), <span class="string">&quot;选择&quot;</span>);</span><br><span class="line"><span class="comment">//显示文件 保存 对话框（最后调用显示对话框）（弹出一个“保存文件”文件选择器对话框）</span></span><br><span class="line">jfc.showSaveDialog(<span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//获取打开的文件</span></span><br><span class="line">File file = jfc.getSelectedFile();</span><br></pre></td></tr></table></figure>


          
        
      
    </div>
    
    
    
    
    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joy_24.gitee.io/myblogs/2020/12/09/swing-jtree/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblogs/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="天行健の博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/myblogs/2020/12/09/swing-jtree/" itemprop="url">Swing开发技巧——JTree篇</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-09T17:12:18+08:00">
                2020-12-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/Swing/" itemprop="url" rel="index">
                    <span itemprop="name">Swing</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  46
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  1
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="设置JTree默认选中根节点"><a href="#设置JTree默认选中根节点" class="headerlink" title="设置JTree默认选中根节点"></a>设置JTree默认选中根节点</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//方法一</span></span><br><span class="line">TreeNode root = (TreeNode)getTreePanel().getTree().getModel().getRoot();<span class="comment">//取得tree的根节点</span></span><br><span class="line">TreePath visiblePath = <span class="keyword">new</span> TreePath(root);</span><br><span class="line">TreeSelectionModel listSelectionModel = getTreePanel().getTree().getSelectionModel();</span><br><span class="line">listSelectionModel.setSelectionPath(visiblePath);</span><br><span class="line"></span><br><span class="line"><span class="comment">//方法二</span></span><br><span class="line">getTreePanel().getTree().setSelectionRow(<span class="number">0</span>);</span><br></pre></td></tr></table></figure>


          
        
      
    </div>
    
    
    
    
    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joy_24.gitee.io/myblogs/2020/12/09/swing-jtable1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblogs/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="天行健の博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/myblogs/2020/12/09/swing-jtable1/" itemprop="url">Swing开发技巧——JTable篇</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-09T16:34:13+08:00">
                2020-12-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/Swing/" itemprop="url" rel="index">
                    <span itemprop="name">Swing</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  881
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  4
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="设置JTable双击表头自动排序"><a href="#设置JTable双击表头自动排序" class="headerlink" title="设置JTable双击表头自动排序"></a>设置JTable双击表头自动排序</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//定义排序器</span></span><br><span class="line"><span class="keyword">private</span> TableRowSorter&lt;DefaultTableModel&gt; tableRowSorter = <span class="keyword">new</span> TableRowSorter&lt;&gt;(getDefaultTableModel());</span><br><span class="line"></span><br><span class="line"><span class="comment">//在创建表格方法中设置排序</span></span><br><span class="line">table.setRowSorter(tableRowSorter);</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="设置JTable显示水平滚动条和垂直滚动条"><a href="#设置JTable显示水平滚动条和垂直滚动条" class="headerlink" title="设置JTable显示水平滚动条和垂直滚动条"></a>设置JTable显示水平滚动条和垂直滚动条</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">jScrollPane = <span class="keyword">new</span> JScrollPane(getTable())</span><br><span class="line"></span><br><span class="line"><span class="comment">//水平滚动条</span></span><br><span class="line">jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);</span><br><span class="line"></span><br><span class="line"><span class="comment">//垂直滚动条</span></span><br><span class="line">jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);</span><br><span class="line"></span><br><span class="line"><span class="comment">//同时需要对JScrollPane中的JTable设置属性</span></span><br><span class="line">table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); </span><br></pre></td></tr></table></figure>

<p>备注：</p>
<p>水平和垂直滚动条总是出现</p>
<p>JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS</p>
<p>JScrollPane.VERTICAL_SCROLLBAR_ALWAYS</p>
<p>水平和垂直滚动条自动出现</p>
<p>JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED</p>
<p>JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED</p>
<hr>
<h1 id="设置JTable表格内容自动换行"><a href="#设置JTable表格内容自动换行" class="headerlink" title="设置JTable表格内容自动换行"></a>设置JTable表格内容自动换行</h1><p>方式一：使用 JTextArea</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">JTable table = <span class="keyword">new</span> JTable();</span><br><span class="line"><span class="comment">//SystemProgramControlPanel为当前的类</span></span><br><span class="line">table.setDefaultRenderer(Object.class, <span class="keyword">new</span> SystemProgramControlPanel.TableViewRenderer());</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     *表格内容渲染，设置自动换行</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@author</span> Administrator</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TableViewRenderer</span> <span class="keyword">extends</span> <span class="title">JTextArea</span> <span class="keyword">implements</span> <span class="title">TableCellRenderer</span></span></span><br><span class="line"><span class="class">    </span>&#123;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">TableViewRenderer</span><span class="params">()</span></span>&#123;</span><br><span class="line">            setOpaque(<span class="keyword">false</span>);</span><br><span class="line">            setLineWrap(<span class="keyword">true</span>); <span class="comment">//利用JTextArea的自动换行方法</span></span><br><span class="line">            setWrapStyleWord(<span class="keyword">true</span>);</span><br><span class="line">            setFont(<span class="keyword">new</span> Font(<span class="string">&quot;宋体&quot;</span>, Font.BOLD, <span class="number">18</span>));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> Component <span class="title">getTableCellRendererComponent</span><span class="params">(JTable table, Object value,</span></span></span><br><span class="line"><span class="function"><span class="params">                                         <span class="keyword">boolean</span> isSelected, <span class="keyword">boolean</span> hasFocus, <span class="keyword">int</span> row, <span class="keyword">int</span> column)</span> </span>&#123;</span><br><span class="line">            <span class="comment">//根据具体需求设置特殊行的颜色(此处和内容换行无关)</span></span><br><span class="line">            <span class="keyword">if</span>(row &gt;= <span class="number">0</span> &amp;&amp; getTable().getValueAt(row,<span class="number">6</span>) != <span class="keyword">null</span>)&#123;</span><br><span class="line">                <span class="keyword">if</span>(<span class="string">&quot;3&quot;</span>.equals(getTable().getValueAt(row,<span class="number">6</span>).toString()))&#123;</span><br><span class="line">                    setForeground(<span class="keyword">new</span> Color(<span class="number">222</span>, <span class="number">173</span>, <span class="number">171</span>, <span class="number">250</span>));</span><br><span class="line">                &#125;<span class="keyword">else</span> <span class="keyword">if</span>(<span class="string">&quot;4&quot;</span>.equals(getTable().getValueAt(row,<span class="number">6</span>).toString()))&#123;</span><br><span class="line">                    setForeground(<span class="keyword">new</span> Color(<span class="number">123</span>, <span class="number">222</span>, <span class="number">157</span>));</span><br><span class="line">                &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                    setForeground(<span class="keyword">new</span> Color(<span class="number">255</span>, <span class="number">253</span>, <span class="number">254</span>, <span class="number">250</span>));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 计算当下行的最佳高度</span></span><br><span class="line">            <span class="keyword">int</span> maxPreferredHeight = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; table.getColumnCount(); i++) &#123;</span><br><span class="line">                setText(<span class="string">&quot;&quot;</span> + table.getValueAt(row, i));</span><br><span class="line">                setSize(table.getColumnModel().getColumn(column).getWidth(), <span class="number">0</span>);</span><br><span class="line">                maxPreferredHeight = Math.max(maxPreferredHeight, getPreferredSize().height);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (table.getRowHeight(row) != maxPreferredHeight)  <span class="comment">// 少了这行则处理器瞎忙</span></span><br><span class="line">                table.setRowHeight(row, maxPreferredHeight);</span><br><span class="line"></span><br><span class="line">            setText(value == <span class="keyword">null</span> ? <span class="string">&quot;&quot;</span> : value.toString());</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>



<p>方式二：使用 JLable </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyCellRenderer</span> <span class="keyword">extends</span> <span class="title">DefaultTableCellRenderer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">MyCellRenderer</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Component <span class="title">getTableCellRendererComponent</span><span class="params">(JTable table, Object value, <span class="keyword">boolean</span> isSelected, 												<span class="keyword">boolean</span> hasFocus, <span class="keyword">int</span> row, <span class="keyword">int</span> column)</span> </span>&#123;</span><br><span class="line">			<span class="comment">//此处通过拼接&lt;html&gt;并放到JLabel中实现内容换行，下面还要计算设置行高</span></span><br><span class="line">            String val = value!=<span class="keyword">null</span>?<span class="string">&quot;&lt;html&gt;&quot;</span>+value.toString()+<span class="string">&quot;&lt;/html&gt;&quot;</span> : <span class="string">&quot;&quot;</span>;</span><br><span class="line">            JLabel label = <span class="keyword">new</span> JLabel(val, JLabel.CENTER);</span><br><span class="line">            label.setFont(<span class="keyword">new</span> Font(<span class="string">&quot;宋体&quot;</span>, Font.BOLD, <span class="number">14</span>));</span><br><span class="line">            label.setForeground(Color.WHITE);</span><br><span class="line">            table.setEnabled(<span class="keyword">true</span>);</span><br><span class="line"><span class="comment">//            label.setBorder(BorderFactory.createLineBorder(Color.red));</span></span><br><span class="line">            <span class="keyword">if</span> (isSelected) &#123;</span><br><span class="line">                label.setOpaque(<span class="keyword">true</span>);</span><br><span class="line">                label.setBackground(getTable().getSelectionBackground());</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span>(row &gt;= <span class="number">0</span> &amp;&amp; getTable().getValueAt(row,<span class="number">6</span>) != <span class="keyword">null</span>)&#123;</span><br><span class="line">                <span class="keyword">if</span>(<span class="string">&quot;3&quot;</span>.equals(getTable().getValueAt(row,<span class="number">6</span>).toString()))&#123;</span><br><span class="line">                    label.setForeground(<span class="keyword">new</span> Color(<span class="number">222</span>, <span class="number">173</span>, <span class="number">171</span>, <span class="number">250</span>));</span><br><span class="line">                &#125;<span class="keyword">else</span> <span class="keyword">if</span>(<span class="string">&quot;4&quot;</span>.equals(getTable().getValueAt(row,<span class="number">6</span>).toString()))&#123;</span><br><span class="line">                    label.setForeground(<span class="keyword">new</span> Color(<span class="number">123</span>, <span class="number">222</span>, <span class="number">157</span>));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 计算当下行的最佳高度</span></span><br><span class="line">            <span class="keyword">int</span> maxPreferredHeight = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">if</span>(column == <span class="number">5</span>)&#123;</span><br><span class="line">                <span class="keyword">double</span> width = label.getPreferredSize().getWidth();</span><br><span class="line">                <span class="keyword">int</span> rowHeight = (<span class="keyword">int</span>) (Math.ceil(width / <span class="number">500</span>) * <span class="number">30</span>);</span><br><span class="line">                maxPreferredHeight = Math.max(maxPreferredHeight, rowHeight);</span><br><span class="line">                table.setRowHeight(row, maxPreferredHeight);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> label;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="获得JTable中的选中行中的数据"><a href="#获得JTable中的选中行中的数据" class="headerlink" title="获得JTable中的选中行中的数据"></a>获得JTable中的选中行中的数据</h1><p>首先假设两个JTable，他们为table1与table2</p>
<p>假设从table1取值放到table2中</p>
<p>1、获得table1的选中行 int index = table1.getSelectedRow();</p>
<p>2、获得table1中列的个数 int column = table1.getColumnCount();</p>
<p>3、取出表格中index行中的值，用集合保存！</p>
<p>（1）创建一个保存的集合Vector&lt;Vector<Object>&gt; vector = Vector&lt;Vector<Object>&gt;();</Object></Object></p>
<p>（2） 再创建一个集合，用于加入到第一个集合 Vector<Object> object = Vector<Object>();</Object></Object></p>
<p>（3）将index行的所有数据取出放入第二个集合中 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">int</span> n= <span class="number">0</span>; n &lt; column; n ++)&#123;</span><br><span class="line">	object.add(table1.getVauleAt(index,n));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>（4）将第二集合中的数据加入到第一个集合中： vector.add(object);</p>
<p>4、创建table2的列名，并用一个集合表示，!</p>
<p>（1）创建一个集合，用于创建列名Vector<Object> object1 = new Vector<Object>();</Object></Object></p>
<p>（2） 为列名赋值，，，，在这里就省略了，具体的名视情况而定！</p>
<p>5、将取出的值加入到table2中：</p>
<p>（1）取得table2的模板DefaultTableModel model = (DefaultTableModel)table2.getModel();</p>
<p>（2）为模板添加内容：model.setDataVector(vector, object1)；</p>
<p>（3）将模板添加到table2中， table2.setModel(model);</p>
<p>大功告成！</p>

          
        
      
    </div>
    
    
    
    
    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
  </section>

  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/myblogs/">&lt;</a><a class="page-number" href="/myblogs/">1</a><span class="page-number current">2</span><a class="page-number" href="/myblogs/page/3/">3</a><a class="page-number" href="/myblogs/page/4/">4</a><a class="extend next" rel="next" href="/myblogs/page/3/">&gt;</a>
  </nav>



          </div>
          


          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/myblogs/uploads/avatar.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                #<a href="/myblogs/archives%7C%7C%20archive">
                <a href="/myblogs/archives">
              
                  <span class="site-state-item-count">34</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/myblogs/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/myblogs/tags/index.html">
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/myblogs/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/joyWJ" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="wangjianjoy@126.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Joy Wang</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/myblogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/myblogs/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/myblogs/js/src/motion.js?v=5.1.4"></script>



  
  

  

  


  <script type="text/javascript" src="/myblogs/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/myblogs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
